import { getUserInfo, login, getDetailInfoById } from '@/api/user'
import { getToken, setToken, removeToken, setTime } from '@/utils/auth'
import { Message } from 'element-ui'
import { resetRouter } from '@/router'
export default {
  namespaced: true,
  state: {
    token: getToken(),
    getUserInfo: {}
  },
  mutations: {
    // 存入token
    changeToken(state, val) {
      setToken(val)
      state.token = getToken()
    },
    // 获取基本数据
    setInfo(state, val) {
      state.getUserInfo = val
    },
    // 删除token
    delToken(state) {
      removeToken()
      state.token = ''
    },
    // 删除基本数据
    delUserInfo(state) {
      state.getUserInfo = {}
    }
  },
  actions: {
    async login(store, data) {
      try {
        const res = await login(data)
        Message.success('登录成功')
        setTime()
        store.commit('changeToken', res)
      } catch (err) {
        console.log(err)
      }
    },
    // 退出登录
    logout(store) {
      store.commit('delToken')
      store.commit('delUserInfo')
      resetRouter()
      store.commit('permission/setRouterList', [], { root: true })
    },
    // 存入基本数据
    async getUserInfo(store) {
      try {
        const basicInfo = await getUserInfo()
        // console.log(basicInfo)
        const detailInfo = await getDetailInfoById(basicInfo.userId)
        const res = {
          ...basicInfo,
          ...detailInfo
        }
        store.commit('setInfo', res)
        // 方便外面可以用变量接受数据
        return res
      } catch (err) {
        console.log(err)
      }
    }
  }
}

